import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
import { z } from 'zod';
import moment from 'moment-timezone';
import axios from 'axios';

async function main() {
  const server = new McpServer({
    name: 'meta-mcp',
    version: '1.0.0',
    capabilities: {
      resources: {},
      tools: {}
    }
  });

  // Tool: current_time
  server.tool(
    'current_time',
    'Get current time',
    {
      format: z.string().default('YYYY-MM-DD HH:mm:ss'),
      timezone: z.string().optional()
    },
    async ({ format, timezone }) => {
      let time = moment();
      if (timezone) {
        time = time.tz(timezone);
      }
      return { content: [{ type: 'text', text: time.format(format) }] };
    }
  );

  // Tool: fetch
  server.tool(
    'fetch',
    'Fetch URL content',
    {
      url: z.string().url()
    },
    async ({ url }) => {
      try {
        const response = await axios.get(url);
        return { content: [{ type: 'text', text: JSON.stringify(response.data) }] };
      } catch (error) {
        // Forward the error message from axios
        throw new Error(error.message);
      }
    }
  );

  // Tool: resolve_library_id
  server.tool(
    'resolve_library_id',
    'Resolve library ID',
    {
      libraryName: z.string()
    },
    async ({ libraryName }) => {
      // This is a placeholder implementation
      return { content: [{ type: 'text', text: `/placeholder/${libraryName}` }] };
    }
  );

  const transport = new StdioServerTransport();
  await server.connect(transport);

  // Keep the process alive to listen for requests
  await new Promise(() => {});
}

main().catch(error => {
  // Per MCP guidelines, log to stderr to avoid corrupting the stdio channel.
  console.error('MCP Server Error:', error);
  process.exit(1);
});